package com.cmhi.softmbh;

import android.app.Activity;
import android.app.DevInfoManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.net.Uri;
import android.opengl.GLSurfaceView;
import android.os.Build;
import android.os.Bundle;
import android.os.Looper;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chinamobile.GetValueListener;
import com.chinamobile.SWDevInfoManager;
import com.cmhi.softmbh.cache.StaticConst;
import com.cmhi.softmbh.entity.Entity;
import com.cmhi.softmbh.entity.UriInfoBean;
import com.cmhi.softmbh.provider.DBUtil;
import com.cmhi.base.receiver.SoftBroadcastReceiver;
import com.cmhi.base.receiver.SoftBroadcastReceiverInterface;
import com.cmhi.softmbh.util.DES;
import com.cmhi.softmbh.util.DeviceUtils;
import com.cmhi.softmbh.util.MyAppUtils;
import com.cmhi.softmbh.util.TMallUtils;
import com.cmhi.softmbh.util.TitanManager;
import com.softmbh.kellyplatform.KellyConst;
import com.softmbh.kellyplatform.KellyPlatform;
import com.softmbh.kellyplatform.bean.AccountBean;
import com.softmbh.kellyplatform.bean.BrandInfo;
import com.softmbh.kellyplatform.bean.BusinessInfoBean;
import com.softmbh.kellyplatform.bean.DeviceUserInfo;
import com.softmbh.kellyplatform.bean.LicenseBean;
import com.softmbh.kellyplatform.bean.ProvinceConfigInfoBean;
import com.softmbh.kellyplatform.util.AppUtils;
import com.softmbh.kellyplatform.util.CheckerUtils;
import com.softmbh.kellyplatform.util.GsonUtils;
import com.softmbh.kellyplatform.util.LocalDeviceInfo;
import com.softmbh.kellyplatform.util.MacUtils;

import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class MainActivity extends Activity implements KellyPlatform.SoftInerface, SoftBroadcastReceiverInterface {
    private LinearLayout llLoading;
    private RelativeLayout rootView;
    //广播接收器
    private SoftBroadcastReceiver softBroadcastReceiver;
    private KellyPlatform kellyPlatform;
    private BusinessInfoBean.DataBean businessDataBean;
    private DeviceUserInfo.DataBean deviceDataBean;
    private UriInfoBean mUriInfoBean;
    private boolean isNeedAllStep = false;
    private String[] thirdApkPkg = {
            "com.gitv.tv.gvp",
            "com.aspirecn.combo.soft",
            "com.zte.authority_jscm",
            "com.jscmcc.ottlogin"
    };

    @Override
    protected void onRestart() {
        super.onRestart();
        AppUtils.debugLog("生命周期=>onRestart");
    }

    private UriInfoBean getUriInfo() {
        AppUtils.debugLog("getUriInfo==");
        UriInfoBean uriInfoBean = null;
        try {
            Uri uri = getIntent().getData();
            if (uri != null) {
                uriInfoBean = new UriInfoBean();
                uriInfoBean.url = URLDecoder.decode(uri.toString().trim(), "UTF-8");//baimeng://softmbh.cmhi.com/player?command=play&vid=11&aid=111
                uriInfoBean.scheme = uri.getScheme();//baimeng
                uriInfoBean.host = uri.getHost();//softmbh.cmhi.com
                uriInfoBean.port = uri.getPort();//-1
                uriInfoBean.path = uri.getPath();///player
                uriInfoBean.playInfo = uri.getQueryParameter("playInfo");//play
                AppUtils.debugLog(uriInfoBean.toString());
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return uriInfoBean;
    }

    /**
     * 调用天猫安装
     *
     * @param packageName
     * @param openUrl
     */
    public void openTransitionByScheme(String packageName, String openUrl) {
        AppUtils.debugLog("调用天猫安装：" + packageName);
        if (TextUtils.isEmpty(packageName)) {
            return;
        }
        Uri uri = Uri.parse("market://com.alibaba.ailabs.geniemarket/transition");
        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
        intent.putExtra("pkgName", packageName);  //包名可以替换自己的需要安装的包名
        intent.putExtra("openUrl", openUrl);
        startActivity(intent);
        finish();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        AppUtils.debugLog("生命周期=>onCreate");
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setContentView(R.layout.activity_main);
        initView();
        initKellyPlatform();
        registerBroadcastReceiver();
        mUriInfoBean = getUriInfo();

        MyAppUtils.reportUserAction(StaticConst.PROVINCE_CODE,
                StaticConst.LAUCHMODE,
                StaticConst.MANU,
                "", StaticConst.MANU, new MyAppUtils.CallBack<String>() {
                    @Override
                    public void onSuccess(String var1) {
                        isNeedAllStep = false;
                        if (BuildConfig.BRAND.equals("ALPS")) {
                            gotoWork();
                        } else if (BuildConfig.BRAND.equals("TMALLGENIE")) {
                            if (!TextUtils.isEmpty(checkThirdPkgInstallAll())) {
                                rootView.setVisibility(View.VISIBLE);
                                openTransitionByScheme(checkThirdPkgInstallAll(), StaticConst.OPEN_RZD_URL);
                            } else {
                                gotoWork();
                            }
                        }
                    }

                    @Override
                    public void onFail(String var1, String var2, int var3) {
                        isNeedAllStep = true;
                        if (BuildConfig.BRAND.equals("ALPS")) {
                            gotoWork();
                        } else if (BuildConfig.BRAND.equals("TMALLGENIE")) {
                            if (!TextUtils.isEmpty(checkThirdPkgInstallAll())) {
                                openTransitionByScheme(checkThirdPkgInstallAll(), StaticConst.OPEN_RZD_URL);
                            } else {
                                gotoWork();
                            }
                        }
                    }
                });
        TitanManager.getInstance().start();
    }

    /**
     * 读本地是否有账号，有账号再读卓望，卓望有账号，去播视频或拉起牌照；
     * 本地无账号，重新走流程
     */
    private void gotoWork() {
        runOnUiThread(() -> {
            String account = DBUtil.query(Entity.ACCOUNT);
            if (!TextUtils.isEmpty(account) && !isNeedAllStep) {
                SWDevInfoManager.getInstance(MainActivity.this.getApplicationContext()).getValue(DevInfoManager.PHONE, MobilePhoneNumber -> {
                    AppUtils.debugLog(DevInfoManager.PHONE + " : " + MobilePhoneNumber);
                    if (!MobilePhoneNumber.isEmpty()) {
                        startAppByLauncher();
                    } else {
                        SWDevInfoManager.getInstance(MainActivity.this.getApplicationContext()).getValue(DevInfoManager.ACCOUNT, Account -> {
                            AppUtils.debugLog(DevInfoManager.ACCOUNT + " : " + Account);
                            if (!Account.isEmpty()) {
                                startAppByLauncher();
                            } else {
                                if (!DBUtil.query(Entity.RESET).equals(Entity.TRUE)) {
                                    rootView.setVisibility(View.VISIBLE);
                                    starKellyPlatform();
                                } else {
                                    try {
                                        hiddenAllView();
                                        MyAppUtils.reportUserAction(StaticConst.PROVINCE_CODE,
                                                StaticConst.LOGIN,
                                                StaticConst.NONE,
                                                "", StaticConst.MANU);
                                        Intent intent = new Intent();
                                        intent.setPackage("com.aspirecn.combo.soft");
                                        intent.setAction("com.aspirecn.combo.soft.activate");
                                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                        startActivity(intent);
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                        showErrorDialogOneBtnExit("打开卓望首活失败!", "退出");
                                    }

                                }
                            }
                        });
                    }
                });
            } else {
                rootView.setVisibility(View.VISIBLE);
                starKellyPlatform();
            }
        });

    }

    private String checkThirdPkgInstallAll() {
        String noInstallPkg = "";
        for (int i = 0; i < thirdApkPkg.length; i++) {
            if (!CheckerUtils.isApkInstall(this, thirdApkPkg[i])) {
                noInstallPkg = thirdApkPkg[i];
                return noInstallPkg;
            }
        }
        return noInstallPkg;
    }

    private void initView() {
        ((TextView) findViewById(R.id.tvVersion)).setText(MyApplication.appVersion);
        llLoading = findViewById(R.id.llLoading);
        rootView = findViewById(R.id.rootView);
        final GLSurfaceView glSurfaceView = findViewById(R.id.surfaceView);
        final SharedPreferences sharedPreferences = getSharedPreferences(StaticConst.SP_FILE_NAME, Context.MODE_PRIVATE);
        if (TextUtils.isEmpty(sharedPreferences.getString(StaticConst.SP_KEY_GPU_VENDOR, ""))) {
            DeviceUtils.getGpuInfo(glSurfaceView, new DeviceUtils.GpuInfo() {
                @Override
                public void onGpuInfo(String gpuSupplier, String gpuRender, String gpuVersion) {
                    AppUtils.debugLog(gpuSupplier + "  " + gpuRender + "  " + gpuVersion);
                    SharedPreferences.Editor editor = sharedPreferences.edit();
                    editor.putString(StaticConst.SP_KEY_GPU_VENDOR, gpuSupplier);
                    editor.putString(StaticConst.SP_KEY_GPU_RENDERER, gpuRender);
                    editor.putString(StaticConst.SP_KEY_GPU_VERSION, gpuVersion);
                    editor.apply();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            glSurfaceView.setVisibility(View.GONE);
                        }
                    });
                }
            });
        } else {
            glSurfaceView.setVisibility(View.GONE);
        }
    }

    private void registerBroadcastReceiver() {
        softBroadcastReceiver = new SoftBroadcastReceiver(this);
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(StaticConst.RECEIVER_ACTION_CDN_UPDATE);
        intentFilter.addAction(StaticConst.RECEIVER_ACTION_ZW_ACTIVATE_COMPLETED);
        intentFilter.addAction(StaticConst.RECEIVER_ACTION_EPG_BACK_PRESSED);
        //RECEIVER_ACTION_ZW_ACTIVATE_FAILER = "com.aspire.jshdc.action.ACTIVATE_FAILER"
        intentFilter.addAction(StaticConst.RECEIVER_ACTION_ZW_ACTIVATE_FAILER);
        registerReceiver(softBroadcastReceiver, intentFilter);
    }

    private void initKellyPlatform() {
        try {
            /**
             * 构造函数
             * @param isTest 是否测试地址
             * @param licenseGroup license 分组 0 正式分组 1 测试分组
             * @param context Activity
             * @param clientId 所在省的clientId
             * @param clientKey 所在省的clientKey
             * @param provinceCode 省编码
             * @param apkBuildTime  apk 打包时间
             * @param isShowLog 是否显示log
             * @param clientMode 渠道号
             * @param isTotalProgress 是否显示一个进度条
             * @param softInerface 回调接口
             * @throws Exception 参数错误报出异常
             */
            String enBrand = BuildConfig.BRAND;
            BrandInfo brandInfo = CheckerUtils.brandInfoMap.get(enBrand);
            DBUtil.update(Entity.BRAND, brandInfo.chineseName);
            DBUtil.update(Entity.EN_BRAND, brandInfo.englishName);
            DBUtil.update(Entity.VENDOR_CODE, brandInfo.vendorCode);
            KellyPlatform.BRAND = enBrand;
            KellyConst.LICENSING_PARTY_CODE = KellyConst.LICENSING_PARTY_OTT_GITV;
            kellyPlatform = new KellyPlatform(StaticConst.KELLY_IS_TEST_SERVER,
                    StaticConst.KELLY_LICENSE_GROUP, this, StaticConst.PROVINCE_CODE, BuildConfig.BUILD_TIMESTAMP,
                    BuildConfig.KELLY_IS_SHOW_LOG, StaticConst.CLIENT_MODE, true,
                    this, KellyPlatform.DEVICE_TYPE_BAIDU_SMART);
            kellyPlatform.DIALOG_LAYOUT = R.layout.dialog_rzd;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void starKellyPlatform() {
        if (DBUtil.query(Entity.RESET).equals(Entity.TRUE)) {
            kellyPlatform.BAIDU_FIRST = false;
        } else {
            kellyPlatform.BAIDU_FIRST = true;
        }
        showLoadingView();
        kellyPlatform.startExecute();
    }

    private void showLoadingView() {
        llLoading.setVisibility(View.VISIBLE);
    }

    private void hiddenAllView() {
        runOnUiThread(() -> llLoading.setVisibility(View.GONE));
    }

    @Override
    protected void onPause() {
        AppUtils.debugLog("onPause");
        super.onPause();
    }

    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(0, 0);
    }

    @Override
    protected void onDestroy() {
        AppUtils.debugLog("onDestroy");
        if (softBroadcastReceiver != null) {
            unregisterReceiver(softBroadcastReceiver);
            softBroadcastReceiver = null;
        }
        if (kellyPlatform != null) {
            kellyPlatform.destroy();
        }
        super.onDestroy();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
            //屏蔽返回键
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    //免密登录
    private void freeLogin(BusinessInfoBean.DataBean businessInfoBean) {
        MyAppUtils.reportUserAction(StaticConst.PROVINCE_CODE,
                StaticConst.LOGIN,
                StaticConst.NONE,
                "", StaticConst.MANU);
        JSONObject bodyJson = new JSONObject();
        try {
            bodyJson.put("Account", businessInfoBean.userAccount);//账号，默认是手机号
            bodyJson.put("Password", "");//密码默认为空
//            bodyJson.put("LisenceType", businessInfoBean.launcherType);//未来电视：icntv,银河：gitv
            bodyJson.put("LisenceType", "gitv");//未来电视：icntv,银河：gitv  小度版本写死银河
            bodyJson.put("ExpiryTime", businessInfoBean.freeTime + "");//免费试用的时长。单位为月
            bodyJson.put("InstallType", businessInfoBean.installType + "");//0：正常安装，1：推送安装

            bodyJson.put("OpeningMode", businessInfoBean.openModel + "");//0：HDC模式1：crm模式
            bodyJson.put("CollectionTime", businessInfoBean.receiveTime);//用户点击领取时间。2020/8/19 12:30
            bodyJson.put("ChargingModel", businessInfoBean.chargeType + "");//收费模式0：free  1：fees
            bodyJson.put("AndroidSDK", "Android" + Build.VERSION.RELEASE);//Android版本号Android4.4
            bodyJson.put("TVMac", MacUtils.getMac());//物理mac
            bodyJson.put("STBMA", businessInfoBean.license);//虚拟MAC
            bodyJson.put("EMMC", (int) CheckerUtils.getTotalMemorySize() / 1024 + "");//内存大小。单位GB。
            bodyJson.put("OTTTerminalType", BuildConfig.OTT_TERMINAL_TYPE);//"TV-OTT"
            bodyJson.put("OTTTerminalBrand", DBUtil.query(Entity.EN_BRAND));//
            bodyJson.put("Manufacturer", businessInfoBean.rzdVendor);//终端厂商"OTT-JS-SOFT"
            bodyJson.put("ModelName", businessInfoBean.rzdModel);//终端型号"SOFT-OTT-A"

            bodyJson.put("STBSN", businessInfoBean.stbId);//STBID（终端唯一标识）
            bodyJson.put("NetType", "0");//网络连接模式0：无线  1：有线

            AppUtils.debugLog("静默登录参数加密前：" + bodyJson.toString());
            String dataInfo = DES.encryptDES(bodyJson.toString(), StaticConst.ZW_INTENT_BASE64_KEY);
            AppUtils.debugLog("静默登录参数加密后：" + dataInfo);
            Intent intent = new Intent();
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setComponent(new ComponentName("com.aspirecn.combo.soft", "com.chinamobile.activate.activity.AutoActivity"));
            intent.putExtra("AccountInfo", dataInfo);
            startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
            rootView.setVisibility(View.VISIBLE);
            MyAppUtils.reportUserAction(StaticConst.PROVINCE_CODE,
                    StaticConst.LOGIN,
                    StaticConst.N,
                    "无法打开登录组件！", StaticConst.MANU);

            showErrorDialogOneBtnExit("无法打开登录组件！", "退出");

        }
    }

    //结束进程
    private void exit() {
        finish();
        //调用系统 API 结束进程
//        android.os.Process.killProcess(android.os.Process.myPid());
        //结束整个虚拟机进程，注意如果在 manifest 里用 android:process 给 APP 指定了不止一个进程，则只会结束当前进程
//        System.exit(0);
    }

    //写入关键参数
    private void writeKeyParameters() {
        try {
            AppUtils.debugLog("writeKeyParameters start");
            //控制卓望首活 APK 正向、反向激活，注释掉则为正向激活，写入 TV-OTT 则为反向激活
            //曾使用值：TV-OTT, 后用：SOFT_TERMINAL, 后移动冷总要求使用 TV-OTT
            //问题记录：2020年3月16日，使用 TV-OTT 银河可以自动登录，使用 SOFT_TERMINAL 银河不能自动登录，且手动登录失败，提示用户不存在
            setZwData(DevInfoManager.OTT_TERMINAL_TYPE, BuildConfig.OTT_TERMINAL_TYPE);
            setZwData(DevInfoManager.OTT_TERMINAL_BRAND, DBUtil.query(Entity.EN_BRAND));
            setZwData(DevInfoManager.CHANNEL_TYPE, BuildConfig.CHANNEL_TYPE);

            //终端厂商：OTT-JS-SOFT, 曾临时用：CMDC, 定版时使用：CMHI
            setZwData(DevInfoManager.MANUFACTURER, "OTT-JS-SOFT");
            //终端型号：SOFT-OTT-A, 曾临时用：CM101s, 定版时使用：RZD-01
            setZwData(DevInfoManager.MODEL_NAME, "SOFT-OTT-A");
            setZwData(DevInfoManager.STB_MAC, DBUtil.query(Entity.VIRTUAL_MAC));
            setZwData(DevInfoManager.STB_SN, DBUtil.query(Entity.VIRTUAL_STBID));
            DBUtil.update(Entity.RZD_VERSION, BuildConfig.VERSION_NAME);
            DBUtil.update(Entity.MANUFACTURER, "OTT-JS-SOFT");
            DBUtil.update(Entity.MODEL_NAME, "SOFT-OTT-A");
            AppUtils.debugLog("writeKeyParameters finish");
        } catch (Exception e) {
            AppUtils.debugLog("writeKeyParameters error : " + e);
            e.printStackTrace();
        }
    }

    @Override
    public void onDownloadComplete(Map<String, String> installPackage) {

    }

    @Override
    public void onLicense(LicenseBean bean) {
        MyAppUtils.platToken = kellyPlatform.getLastToken();
        DBUtil.update(Entity.APP_TOKEN, kellyPlatform.getLastToken());
        //软终端虚拟 mac 地址
        DBUtil.update(Entity.VIRTUAL_MAC, bean.license);
        //软终端 stbId
        DBUtil.update(Entity.VIRTUAL_STBID, bean.stbId);
        DBUtil.update(Entity.BASE_INFO, kellyPlatform.getBaseInfo());
        //license 组别，0: 正式组，1: 测试组
        DBUtil.update(Entity.LICENSE_GROUP, bean.licenseGroup + "");
        DBUtil.update(Entity.STBID, bean.stbId);
        DBUtil.update(Entity.PROVINCE_ID, StaticConst.PROVINCE_CODE);
        DBUtil.update(Entity.AREA_CODE, StaticConst.PROVINCE_CODE);
        DBUtil.update(Entity.OS_VERSION, Build.VERSION.RELEASE);
        DBUtil.update(Entity.STB_TYPE, "0");
        DBUtil.update(Entity.SETTING_ACTION, "com.cmhi.softmbh.SETTINGS");
        writeKeyParameters();


        SWDevInfoManager.getInstance(MainActivity.this).getValue(DevInfoManager.LAUNCHER, new GetValueListener() {
            @Override
            public void onResponse(String launcher) {
                if (TextUtils.isEmpty(launcher)) {//如果为空，说明是首次与卓望交互,静默登录
                    getUserInfoByDivice();
                } else {
                    if (TextUtils.isEmpty(DBUtil.query(Entity.RESET))) {
                        getUserInfoByDivice();
                    } else {
                        onReadZWAccount();
                    }
                }
            }
        });
        if (isNeedAllStep) {
            MyAppUtils.reportUserAction(StaticConst.PROVINCE_CODE,
                    StaticConst.LAUCHMODE,
                    StaticConst.MANU,
                    "", StaticConst.MANU);
        }
    }

    private void getUserInfoByDivice() {
        String apiAccessToken = "";
        String deviceId = "";
        if (BuildConfig.BRAND.equals("ALPS")) {
            apiAccessToken = getIntent().getStringExtra("apiAccesstoken");
            deviceId = getIntent().getStringExtra("CMCC_DEVICE_ID");
        } else if (BuildConfig.BRAND.equals("TMALLGENIE")) {
            deviceId = TMallUtils.getDeviceId();
        }
        if (!TextUtils.isEmpty(apiAccessToken)) {
            kellyPlatform.getUserInfoByDivice("baiduToken", apiAccessToken);
        } else if (!TextUtils.isEmpty(deviceId)) {
            kellyPlatform.getUserInfoByDivice("deviceId", deviceId);
        } else {
            showErrorDialogOneBtnExit("获取的deviceId为空!", "退出");
        }
    }

    @Override
    public void onProvinceInfo(ProvinceConfigInfoBean.DataBean dataBean, LocalDeviceInfo
            localDeviceInfo) {

    }


    @Override
    public void onProgress(String packageName, String apkName, int progress) {

    }

    private boolean isInMainThread() {
        Looper myLooper = Looper.myLooper();
        Looper mainLooper = Looper.getMainLooper();
        AppUtils.debugLog("isInMainThread myLooper=" + myLooper
                + ";mainLooper=" + mainLooper);
        return myLooper == mainLooper;
    }

    @Override
    public void onConfirmComplete() {
        AppUtils.debugLog("onConfirmComplete->isInMainThread:" + isInMainThread());
        updateZWCND();
        SWDevInfoManager.getInstance(MainActivity.this).getValue(DevInfoManager.LAUNCHER, new GetValueListener() {
            @Override
            public void onResponse(String launcher) {
                if (launcher.equals("com.gitv.launcher.soft")) {
                    DBUtil.update(Entity.LICENSE_CODE, "gitv");
                } else if (launcher.equals("tv.icntv.ott.soft")) {
                    DBUtil.update(Entity.LICENSE_CODE, "icntv");
                }
                DBUtil.update(Entity.LAUNCHER_ACTION, launcher);
                startAppByLauncher();
            }
        });
    }

    @Override
    public void onBusinessInfo(BusinessInfoBean.DataBean dataBean) {
        businessDataBean = dataBean;
        String account = DBUtil.query(Entity.ACCOUNT);
        AppUtils.debugLog("获取到手机号：" + deviceDataBean.phone + "  已登录的账号为：" + ((TextUtils.isEmpty(account)) ? "未登录" : account));
        if (TextUtils.isEmpty(account)) {
            businessDataBean.userAccount = deviceDataBean.phone;
        } else {//切换和家亲账号，还用之前的账号登录
            businessDataBean.userAccount = account;
        }
        freeLogin(businessDataBean);
    }

    @Override
    public void onUserInfoByDevice(DeviceUserInfo.DataBean bean) {
        deviceDataBean = bean;
        kellyPlatform.getBusinessInfo();
    }

    @Override
    public void onUserContinue(byte b) {

    }

    @Override
    public void onNetStateChange(boolean isConnect) {

    }

    @Override
    public void onAccountInfo(String s, List<AccountBean> list) {

    }

    @Override
    public void onMediaCodecLevel(String s) {
        DBUtil.update(Entity.FOUR_THOUSAND, s);
    }

    /**
     * 接收到广播，处理
     *
     * @param intent
     */
    @Override
    public void onReceive(Intent intent) {
        String action = intent.getAction();
        AppUtils.debugLog("收到广播：action：" + action);
        if (action.equals(StaticConst.RECEIVER_ACTION_CDN_UPDATE)) {//CDN改变
            updateZWCND();
        } else if (action.equals(StaticConst.RECEIVER_ACTION_EPG_BACK_PRESSED)) {//牌照方按返回键
            String fromEPG = intent.getStringExtra("fromEPG");
            com.softmbh.kellyplatform.util.AppUtils.debugLog("fromEPG : " + fromEPG);
            exit();
        } else if (action.equals(StaticConst.RECEIVER_ACTION_ZW_ACTIVATE_COMPLETED)) {//卓望激活完成
            MyAppUtils.reportUserAction(StaticConst.PROVINCE_CODE,
                    StaticConst.LOGIN,
                    StaticConst.Y,
                    "", StaticConst.MANU);

            receiveActivateCompleted();
        } else if (action.equals(StaticConst.RECEIVER_ACTION_ZW_ACTIVATE_FAILER)) {//卓望激活失败
            String code = intent.getStringExtra("code");
            String message = intent.getStringExtra("message");
            hiddenAllView();
            MyAppUtils.reportUserAction(StaticConst.PROVINCE_CODE,
                    StaticConst.LOGIN,
                    StaticConst.N,
                    message, StaticConst.MANU);

            showErrorDialog("错误", "卓望认证", message, true, "", "退出", new KellyPlatform.DialogCallback() {
                @Override
                public void onButtonClick(String buttonText) {
                    exit();
                }
            });
        }
    }

    private void updateZWCND() {
        SWDevInfoManager.getInstance(this.getApplicationContext()).getValue(DevInfoManager.CDN_TYPE, cdnType -> {//华为：HW，中兴：ZTE
            try {
                AppUtils.debugLog("updateZWCND " + cdnType + "  start");
                if (cdnType.equals("HW")) {
                    setZwData(DevInfoManager.EPG_ADDRESS, "http://223.110.245.22:33200/EPG");
                    setZwData(DevInfoManager.CDN_ADDRESS, "http://183.207.248.71:80");
                    setZwData(DevInfoManager.CDN_ADDRESS_BACK, "http://183.207.249.71:80");
                } else {
                    //软终端默认调用中兴 CDN，卓望软终端鉴权默认数据为中兴 CDN
                    setZwData(DevInfoManager.EPG_ADDRESS, "http://223.110.239.37:9330/EPG");
                    setZwData(DevInfoManager.CDN_ADDRESS, "http://223.110.239.40:6060");
                    setZwData(DevInfoManager.CDN_ADDRESS_BACK, "http://223.110.240.40:6060");
                }
                AppUtils.debugLog("updateZWCND " + cdnType + "  finish");
            } catch (Exception e) {
                AppUtils.debugLog("updateZWCND " + cdnType + "  error : " + e);
                e.printStackTrace();
            }
        });

    }

    private void onReadZWAccount() {
        SWDevInfoManager.getInstance(this.getApplicationContext()).getValue(DevInfoManager.PHONE, MobilePhoneNumber -> {
            AppUtils.debugLog(DevInfoManager.PHONE + " : " + MobilePhoneNumber);
            if (!MobilePhoneNumber.isEmpty()) {
                getZwAccountOrPhoneDo(MobilePhoneNumber);
            } else {
                SWDevInfoManager.getInstance(this.getApplicationContext()).getValue(DevInfoManager.ACCOUNT, Account -> {
                    AppUtils.debugLog(DevInfoManager.ACCOUNT + " : " + Account);
                    if (!Account.isEmpty()) {
                        getZwAccountOrPhoneDo(Account);
                    } else {
                        if (TextUtils.isEmpty(DBUtil.query(Entity.RESET))) {
                            getUserInfoByDivice();
                        } else {
                            try {
                                hiddenAllView();
                                MyAppUtils.reportUserAction(StaticConst.PROVINCE_CODE,
                                        StaticConst.LOGIN,
                                        StaticConst.NONE,
                                        "", StaticConst.MANU);
                                Intent intent = new Intent();
                                intent.setPackage("com.aspirecn.combo.soft");
                                intent.setAction("com.aspirecn.combo.soft.activate");
                                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                startActivity(intent);
                            } catch (Exception e) {
                                e.printStackTrace();
                                showErrorDialogOneBtnExit("打开卓望首活失败!", "退出");
                            }

                        }
                    }
                });
            }
        });
    }


    private void getZwAccountOrPhoneDo(String zwAccount) {
        String currentAccount = zwAccount.replace("reg", "").replace("NJ", "");
        String account = DBUtil.query(Entity.ACCOUNT);
        String stbId = DBUtil.query(Entity.VIRTUAL_STBID);
        String phone = "";
        if (!TextUtils.isEmpty(currentAccount)) {
            DBUtil.update(Entity.ACCOUNT, currentAccount);
            try {
                kellyPlatform.fireLicense(stbId, currentAccount, phone);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void receiveActivateCompleted() {
        showLoadingView();
        DBUtil.update(Entity.USER_STATE, "1");//0 未激活 1 已激活
        onReadZWAccount();
    }


    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
    }

    //根据 launcher 属性值拉起对应 APP
    private void startAppByLauncher() {
        updateZWCND();
        hiddenAllView();
        MyAppUtils.reportUserAction(StaticConst.PROVINCE_CODE,
                StaticConst.LAUNCHER_SUCCESS,
                StaticConst.NONE,
                "", StaticConst.MANU);

        try {
            AppUtils.debugLog("start GITV");
            Intent intent = new Intent();
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            ComponentName componentName = new ComponentName("com.gitv.tv.gvp", "com.gitv.tv.gvp.activity.WelcomeActivity");
            if (mUriInfoBean != null) {
                String playInfo = mUriInfoBean.playInfo;
                if (!TextUtils.isEmpty(playInfo)) {
                    AppUtils.debugLog("播放信息playInfo:" + playInfo);
                    Map<String, Object> playInfoMap = new HashMap<>();
                    playInfoMap = GsonUtils.jsonToBean(playInfo, playInfoMap.getClass());
                    AppUtils.debugLog("播放信息playInfoMap:" + playInfoMap.toString());
                    if (playInfoMap.containsKey("action2")) {
                        playInfoMap.remove("action");
                    }
                    if (playInfoMap != null && playInfoMap.size() > 0) {
                        for (Map.Entry<String, Object> entry : playInfoMap.entrySet()) {
                            String value = String.valueOf(entry.getValue());
                            if ("action2".equals(entry.getKey())) {
                                intent.setAction(value);
                                intent.putExtra("action", value);
                                AppUtils.debugLog("intent.put->action" + ": " + value);
                            } else {
                                if ("action".equals(entry.getKey())) {
                                    intent.setAction(value);
                                }
                                intent.putExtra(entry.getKey(), value);
                                AppUtils.debugLog("intent.put->" + entry.getKey() + ": " + value);
                            }
                        }
                    }
                } else {
                    intent.setComponent(componentName);
                }
            } else {
                intent.setComponent(componentName);
            }
            startActivity(intent);
            overridePendingTransition(0, 0);
            AppUtils.debugLog("start GITV finish");
            MyAppUtils.reportUserAction(StaticConst.PROVINCE_CODE,
                    StaticConst.LAUNCHER_SUCCESS,
                    StaticConst.Y,
                    "", StaticConst.MANU);
            llLoading.postDelayed(this::exit, 2000);
        } catch (Exception e) {
            AppUtils.debugLog("start GITV error : " + e);
            e.printStackTrace();
            rootView.setVisibility(View.VISIBLE);
            MyAppUtils.reportUserAction(StaticConst.PROVINCE_CODE,
                    StaticConst.LAUNCHER_SUCCESS,
                    StaticConst.N,
                    "打开银河桌面失败！", StaticConst.MANU);
            showErrorDialogOneBtnExit("打开银河桌面失败！", "退出");
        }
    }

    private void showErrorDialog(String mainTitle, String subTitle, String message,
                                 boolean isShowHit, String buttonText1, String buttonText2, KellyPlatform.DialogCallback
                                         dialogCallback) {
        runOnUiThread(() -> kellyPlatform.showErrorMessage(mainTitle, subTitle, message, isShowHit, buttonText1, buttonText2, dialogCallback));
    }

    private void showErrorDialogOneBtnExit(String message, String buttonText2) {
        hiddenAllView();
        showErrorDialog("错误", "", message, false, "", buttonText2, new KellyPlatform.DialogCallback() {
            @Override
            public void onButtonClick(String buttonText) {
                exit();
            }
        });
    }

    //读取卓望数据
    private void getZwData(String key) {
        SWDevInfoManager
                .getInstance(this)
                .getValue(key, value ->
                        AppUtils.debugLog(key + " : " + value));
    }

    //写入卓望数据
    private void setZwData(String key, String value) {
        SWDevInfoManager.getInstance(this.getApplicationContext())
                .update(key,
                        value,
                        DevInfoManager.Default_Attribute,
                        result -> {// 0 成功，否则失败
                            AppUtils.debugLog(key + " : " + value + " : " + (result == 0 ? "success" : result));
                        });
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
        AppUtils.debugLog("onLowMemory");
    }

    @Override
    public void onTrimMemory(int level) {
        super.onTrimMemory(level);
        AppUtils.debugLog("onTrimMemory level: " + level);
    }
}
